<?php

namespace admin\controllers;

use Yii;
use common\helpers\Pager;
use common\helpers\Uploader;
use common\models\Design;
use common\models\Category;

class DesignController extends Controller {

    // 设置所属一级导航 不设置表示 就是当前类名
    public $parent = 'member';

    /**
     * showing Design list
     * @return string
     */
    public function actionDesignList()
    {
        if( ! $this->isJson) {
            return $this->render('design-list', [
                'modelSelector' => Category::selector($this->params['designModelCategories']),
            ]);
        }
        $params = $this->request->post();
        $params['category_id'] = max($params['category_id']);
        foreach(['start', 'end'] as $key) {
            if($params[$key]) {
                $params[$key] = strtotime($params[$key]);
            }
        }
        $params['deleted_at'] = 0;
        $query = Design::filterConditions(Design::initCondition([['title', 'like'], 'category_id', 'user_id', 'device', 'level', 'model', ['created_at', '>=', 'start'], ['created_at', '<=', 'end'], 'platform', 'deleted_at'], $params));
        $data['page'] = Pager::page(['page_count' => 20, 'total_count' => $query->count()]);
        $data['infos'] = $query->with('designer')->orderBy('id desc')->offset(Pager::offset())->limit(Pager::limit())->asArray()->all();
        return $this->json($data);
    }

    /**
     * show design information
     * @param id int by get request
     * @return string
     */
    public function actionDesignDetail()
    {
        $design = null;
        $designId = $this->request->get('id');
        if( ! $design = Design::canEdit($designId)) {
            return $this->error('无效的作品（Invalid Design）', 'design/design-list');
        }
        return $this->render('design-detail', [
            'data' => $design,
            'modelSelector' => Category::selector($this->params['designModelCategories']),
        ]);
    }
    /***
     * 上传图片操作
     * @param $upload array files
     * @return string file path json
     */
    function actionDesignUploader()
    {
        $params = require Yii::getAlias('@common/config/uploader.php');
        // 上传操作
        $uploader = (new Uploader($params['design']))->upload('upload');
        // $this->setStatus($uploader['code'], $uploader['message']);
        return $this->json($uploader);
    }
    /**
     * update design information
     * @describe use get(id) to find Design
     * @return string html
     */
    public function actionDesignUpdate()
    {
        /* @var $design Design */
        // id 为必填项，判断作品存在状态
        $design = Design::canEdit($this->request->get('id'));
        // 未得到，渲染错误页面
        if( ! $design) {
            return $this->error('无效的作品（Invalid Design）', 'design/design-list');
        }
        $param = $this->request->post();
        $param['category_id'] = max($param['category_id']);
        $design->load(['Design' => $param], 'Design');
        if ( ! $design->validate()) {
            // 参数异常，渲染错误页面
            return $this->error($design->errors(), 'design/design-detail?id='.$design->id);
        }
        if ($design->save()) {
            // 保存成功
            return $this->success('作品（'.$design->title.'）更新成功（Update Success）', [
                ['title' => '前往作品列表页', 'url' => 'design/design-list'],
                ['title' => '继续修改作品', 'url' => 'design/design-detail?id='.$design->id]
            ]);
        }
        // 参数异常，渲染错误页面
        return $this->error('作品（'.$design->title.'）更新失败，请重试（System Error）', 'design/design-detail?id='.$design->id);
    }
    /**
     * delete Design
     * @param ids array post request
     * @return string json
     */
    public function actionDesignDelete()
    {
        if( ! (($ids = $this->request->post('id')) || ($ids = $this->request->post('ids')))) {
            return $this->json('Invalid.Param', '请求异常（Invalid Param）');
        }
        else if(Design::trashAll(['id' => $ids])) {
            return $this->json(SuccessCode, '作品删除成功（Delete Success）');
        }
        return $this->json('System.Error', '作品删除失败（System Error）');
    }
}